// 检查是否数组
export const isArray = (arr) => {
    return Object.prototype.toString.call(arr) === "[object Array]";
  };
  
  // 检查是否数值
  export const isNumber = (num) => {
    return Object.prototype.toString.call(num) === "[object Number]";
  };
  
  // 判断是否对象
  export const isObject = (obj) => {
    return Object.prototype.toString.call(obj) === "[object Object]";
  };
  
  // 正则取数值
  export const getNumber = (str) => {
    const reg = /\d+/g;
    const arr = str.match(reg);
    const num = arr.join(".");
    return num;
  };
  
  // 获取字符串里面的对象
  export const getObj = (str) => {
    const reg = /{.*}/g;
    const obj = str.match(reg);
    return obj;
  };
  
  // 正则判断非数值
  export const isNotNumber = (str) => {
    const reg = /[^0-9]/g;
    return reg.test(str);
  };
  
  /**
   * 将url字符串解析成对象
   * @param  {String} str 地址参数
   * @param  {Boolean} unEncodeURI 不使用编码
   * @return {Object} 转换之后的url参数
   */
  export const url2Object = (val = "", unDecodeURI = false) => {
    let result = {};
    const isQuestion = val.includes("?");
    const query = isQuestion ? val.split("?")[1] : val;
    const arr = query.split("&");
    arr.forEach((item, idx) => {
      let param = item.split("="),
        name = param[0],
        value = param[1] || "";
      if (name) {
        result[name] = unDecodeURI ? value : decodeURIComponent(value);
      }
    });
    return result;
  };
  
  /**
   * 将对象解析成url字符串
   * @param  {Object} obj 参数对象
   * @param  {Boolean} unEncodeURI 不使用编码
   * @return {String} 转换之后的url参数
   */
  export const object2Url = (obj = {}, unEncodeURI = false) => {
    let result = [];
    for (let name of Object.keys(obj)) {
      let value = obj[name];
      if (value) {
        result.push(
          name + "=" + (unEncodeURI ? value : encodeURIComponent(value))
        );
      }
    }
    if (result.length) {
      return "?" + result.join("&");
    } else {
      return "";
    }
  };
  
  /**
   * 数组上移
   * @param {Array} arr 数组
   * @param {Number} index 当前索引
   * @return {Array} 上移后的数组
   * @example
   * arrayUp([1,2,3,4,5], 2) => [1,3,2,4,5]
   */
  export const arrayUp = (arr, index) => {
    if (index === 0) return;
    arr[index] = arr.splice(index - 1, 1, arr[index])[0];
  };
  
  /**
   * 数组下移
   * @param {Array} arr 数组
   * @param {Number} index 当前索引
   * @return {Array} 下移后的数组
   * @example
   * arrayDown([1,2,3,4,5], 2) => [1,2,4,3,5]
   */
  export const arrayDown = (arr, index) => {
    if (index === arr.length - 1) return;
    arr[index] = arr.splice(index + 1, 1, arr[index])[0];
  };
  
  /**
   * 深拷贝
   * @param {Object} obj 对象
   * @return {Object} 拷贝后的对象
   */
  export const deepClone = (obj) => {
    let _obj = JSON.stringify(obj),
      objClone = JSON.parse(_obj);
    return objClone;
  };
  
  /**
   * sku排序算法
   * @param {Array} arr sku数组
   * @return {Array} 排序后的sku数组
   */
  // sku排列算法
  export function cartesianProductOf() {
    return Array.prototype.reduce.call(
      arguments,
      function (a, b) {
        var ret = [];
        a.forEach(function (a) {
          b.forEach(function (b) {
            ret.push(a.concat([b]));
          });
        });
        return ret;
      },
      [[]]
    );
  }
  
  /**
   * 线程休眠
   * @param {Number} time 休眠时间
   * @return {Promise} 休眠后的promise
   * @example
   * sleep(1000).then(() => {
   * console.log('休眠结束')
   * })
   */
  export const sleep = (time) => {
    return new Promise((resolve) => setTimeout(resolve, time));
  };
  
  /**
   * 正则替换html标签
   * @param {String} str 字符串
   * @return {String} 替换后的字符串
   * @example
   * replaceHtmlTag('<div>123</div>') => 123
   */
  export const replaceHtml = (str) => {
    const reg = /<[^>]+>/g;
    return str.replace(reg, "");
  };
  
  /**
   * url地址转对象
   * @param {String} str url字符串，如abc=1&b=2
   * @return {Object} 转换后的对象
   * @example
   * urlQueryToObject('?a=1&abc=1&b=2/') => { a:1 , abc: '1', b: '2' }
   */
  export const urlQueryToObject = (url, decode) => {
    const query = url.split("?")[1] || "";
    const params = query.split("&");
    const result = {};
    params.forEach((item) => {
      const [key, value] = item.split("=");
      result[key] = decode ? decodeURIComponent(value) : value;
    });
    return result;
  };
  
  /**
   * 随机数指定范围的最小值最大值
   * @param {Number} min 最小值
   * @param {Number} max 最大值
   * @return {Number} 随机数
   * @example
   * random(1, 10) => 5
   */
  export const randomChoiceNum = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  };
  
  /**
   * 判断是否以数值加逗号开头
   * @param {String} str 字符串
   * @return {Boolean} 是否以数值加逗号开头
   * @example
   * isNumberComma('1,123') => true
   */
  export const isNumberComma = (str) => {
    const reg = /^[0-9,]+$/;
    return reg.test(str);
  };
  
  /**
   * 获取主域名
   * @param {String}
   * @return {String}
   **/
  export const domain = (val) => {
    return /(http|https):\/\/(www.)?(\w+(\.)?)+/.exec(val)[0];
  };
  
  /**
   * 对象转成&连接的字符串
   * @param {Object} obj 对象
   * @return {String} 字符串
   */
  export const obj2Url = (obj) => {
    let str = "";
    for (let key in obj) {
      str += `&${key}=${obj[key]}`;
    }
    return str;
  };
  
  /**
   * 获取数据类型
   * @param {Any} any 任意类型
   * @return {Any} any
   *
   * @example getType(null)=>Null;
   * */
  export const getType = (any) => {
    const temp = Object.prototype.toString.call(any);
    const type = temp.replace(/\[/g, "").replace(/\]/g, "");
    const index = type.lastIndexOf(" ");
    const str = type.substring(index + 1, type.length);
    return str;
  };
  
  // 是否为false - https://www.cnblogs.com/cisum/p/12072873.html
  export const isTrue = (any) => {
    let match = [
      "undefined",
      "null",
      "NaN",
      "false",
      false,
      0,
      undefined,
      NaN,
      "",
      null,
    ];
    return match.indexOf(any) > -1 ? false : true;
  };
  
  /**
   * 过滤值为null,undefined等空值
   * @param {Object} obj 传入对象
   * @param {Boolean} back 是否返回空值为空字符串
   * @return {Object} {}
   **/
  export const filterEmptyObject = (obj, back = false) => {
    const isObject = getType(obj) === "Object" ? true : false;
    if (isObject) {
      for (const i in obj) {
        if (!isTrue(obj[i])) {
          if (back) {
            obj[i] = "";
          } else {
            delete obj[i];
          }
        }
      }
      return obj;
    }
    return {};
  };
  
  /**
   * 根据token生成汉字昵称
   */
  export const generateUserInfo = (token) => {
    const arr = token.split("");
    const cn = arr.map((v) =>
      String.fromCharCode(v.charCodeAt() + 0x4e00 - 0x30)
    );
    const nickname = cn.slice(0, 5).join("");
    return {
      nickname,
    };
  };